<template>
<div>
    <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button>
    <el-dialog  title="提示"
  :visible.sync="dialogVisible"
  :before-close="handleClose">
        <div class="topbox">
            <el-form :model="ruleForm" :rules="rules" :label-position="labelPosition" ref="dialogFormRef" label-width="80px" class="demo-ruleForm">
                <el-form-item label="模板名称" prop="name">
                    <el-input style="width: 430px" clearable v-model="ruleForm.name" maxlength="20"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <div id="AlarmSmsTemplate" class="zhfz_systemSetting">
            <div class="AlarmSmsTemplate_cnt">
                <div class="AlarmSmsTemplate_title">
                    <span style="color:red">*</span>
                    <div>模板内容</div>
                </div>
                <div id="AlarmSmsTemplate_add" :class="{AlarmSmsTemplate_add_blue:skin=='skinTwo'}" class="bd_input" v-html="msgStr" contenteditable="true"></div>
                <div id="AlarmSmsTemplate_rightbox">
                    <div class="rightbox_title">
                        <p>短信动态属性标签，请点击插入</p>
                    </div>
                    <div class="rightbox__btn">
                        <el-button type="primary" @click="btnClick('<姓名>', '<张三>')">姓名</el-button>
                        <el-button type="primary" @click="btnClick('<人员类型>', '<未成年>')">人员类型</el-button>
                        <el-button type="primary" @click="btnClick('<报警类型>', '<手环电量低>')">报警类型</el-button>
                        <el-button type="primary" @click="btnClick('<区域名称>', '<武汉市>')">区域名称</el-button>
                    </div>
                </div>
            </div>
            <div class="leftbox_text">
                <p id="leftboxtext">示例:{{ leftboxtext }}</p>
            </div>
        </div>
        <div slot="footer">
            <el-button type="primary" @click="dialogSave('dialogFormRef')">确定</el-button>
            <el-button @click="handleClose('dialogFormRef')">取消</el-button>
            <slot name="footerExtraSlot"></slot>
        </div>
    </el-dialog>
</div>
    
</template>

<script>
export default {
    components: {},
    computed: {
        skin () {
            return 'skinTwo'
        }
    },
    data() {
        return {
            //div输入框数据
            textContent: '',
            msgStr: '',
            leftboxtext: '',
            //表单label显示位置
            labelPosition: 'left',
            leftboxtext: '示例:',
            //	默认的dialog属性
            dialogVisible: false,
            ruleForm: {
                name: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    {
                        min: 2,
                        max: 20,
                        message: '长度在 2 到 20 个字符',
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    mounted() {
        this.monitor(); // 注册-删除键按下事件
        this.monitorup(); // 注册-删除键抬起事件
        this.onkeyup(); // 注册-按键抬起事件
    },
    beforeDestroy(){
        console.log('监听事件销毁 beforeDestroy')
        // 监听事件销毁
        document.onkeydown = undefined
        document.onkeyup = undefined
    },
    destroyed(){
        console.log('监听事件销毁 destroyed')
        // 监听事件销毁
        document.onkeydown = undefined
        document.onkeyup = undefined
    },
    methods: {
        // 光标失去焦点事件
        // 定义-删除键按下事件
        monitor: function() {
            var that = this;
            document.onkeydown = function(e) {
                //按下回车提交
                let key = window.event.keyCode;
                //事件中keycode=13为回车事件
                if (key == 8) {
                    that.loginnow();
                }
            };
        },
        // 定义-删除键抬起事件
        monitorup: function() {
            var that = this;
            document.onkeyup = function(e) {
                //按下回车提交
                let key = window.event.keyCode;
                //事件中keycode=13为回车事件
                if (key == 8) {
                    that.loginnowup();
                }
            };
        },
        // 定义-按键抬起事件
        onkeyup: function() {
            var that = this;
            document.onkeyup = function(e) {
                //
                that.loginnowkeyup();
            };
        },
        // 删除键按下回调
        loginnow: function() {
            // 删除键按下
            let divbtn = document.querySelector('#AlarmSmsTemplate_add');
            // this.leftboxtext = divbtn.innerText;
        },
        // 删除键抬起回调
        loginnowup: function() {
            // 删除键抬起
            // let divbtn = document.querySelector("#span_add");
            // this.leftboxtext = divbtn.innerText;
        },
        // 键盘抬起事件回调
        loginnowkeyup() {
            // 键盘抬起事件
            let divbtn = document.querySelector('#AlarmSmsTemplate_add');
            if (document.querySelector('#AlarmSmsTemplate_add') !== null) {
                var exhibition = document.querySelector('#AlarmSmsTemplate_add').innerText;
            }
            console.log(exhibition, 111)
            // 输入框数据和示例数据同步处理
            var mark = exhibition.split('<');
            var lable = '';
            for (var i = 0; i < mark.length; i++) {
                if (mark[i].indexOf('>') != -1) {
                    var otherOne = mark[i].substring(0, mark[i].indexOf('>') + 1);
                    var otherTwo = mark[i].substring(mark[i].indexOf('>') + 1);
                    if ('姓名>' == otherOne) {
                        otherOne = '<张三>';
                    }
                    if ('人员类型>' == otherOne) {
                        otherOne = '<未成年>';
                    }
                    if ('报警类型>' == otherOne) {
                        otherOne = '<手环电量低>';
                    }
                    if ('区域名称>' == otherOne) {
                        otherOne = '<天津市>';
                    }
                    lable += otherOne + otherTwo;
                } else {
                    lable += mark[i];
                }
            }
            var ShiLi = document.getElementById('leftboxtext');
            // ShiLi.innerHTML = noteExample + lable;
            this.leftboxtext = lable;
        },
        // 功能按钮点击事件
        btnClick(msg, data) {
            // 点击触发时，将光标聚焦到div文本边框上
            document.querySelector('#AlarmSmsTemplate_add').focus();
            var divContent = document.querySelector('#AlarmSmsTemplate_add').innerText;
            //判断输入框是否有内容
            if (divContent != '') {
                this.insertHtmlAfterRange('<span class="boxspan input_font_color"  style="display: inline-block; cursor: move;" contenteditable="false">' + msg + '</span>');
            } else {
                // 输入框初始无内容时直接进行数据拼接处理
                let clickmsg = '<span class="boxspan input_font_color" style="cursor: move;" contenteditable="false">' + msg + '</span>';
                let divbtn = document.querySelector('#AlarmSmsTemplate_add');
                this.msgStr = divbtn.innerHTML += clickmsg;
                this.leftboxtext += data;
            }
            // 调用数据处理，进行示例: 数据同步
            this.$nextTick(() => {
                this.loginnowkeyup();
            });
            // 【重要-功能取消，使用给div绑定fouces】光标移至最后
            // this.$nextTick(() => {
            //   this.keepLastIndex(document.querySelector("#AlarmSmsTemplate_add"));
            // });
        },
        // 光标失去焦点后-移至最后
        keepLastIndex(obj) {
            if (window.getSelection) {
                //ie11 10 9 ff safari
                obj.focus(); //解决ff不获取焦点无法定位问题
                var range = window.getSelection(); //创建range
                range.selectAllChildren(obj); //range 选择obj下所有子内容
                range.collapseToEnd(); //光标移至最后
            } else if (document.selection) {
                //ie10 9 8 7 6 5
                var range = document.selection.createRange(); //创建选择对象
                //var range = document.body.createTextRange();
                range.moveToElementText(obj); //range定位到obj
                range.collapse(false); //光标移至最后
                range.select();
            }
        },
        // 验证浏览器，做ie/谷歌 getSelection、createRange兼容
        isSupportRange() {
            return typeof document.createRange === 'function' || typeof window.getSelection === 'function';
        },
        // 获取光标位置
        getCurrentRange() {
            let range = null;
            let selection = null;
            if (isSupportRange()) {
                selection = document.getSelection();
                if (selection.getRangeAt && selection.rangeCount) {
                    range = document.getSelection().getRangeAt(0);
                }
            } else {
                range = document.selection.createRange();
            }
            return range;
        },
        // 光标位置插入button点击内容
        insertHtmlAfterRange(html) {
            let selection = null;
            let range = null;
            if (this.isSupportRange()) {
                // IE > 9 and 其它浏览器
                selection = document.getSelection();
                if (selection.getRangeAt && selection.rangeCount) {
                    let fragment, node, lastNode;
                    range = selection.getRangeAt(0);
                    range.deleteContents();
                    let el = document.createElement('span');
                    el.innerHTML = html;
                    // 创建空文档对象,IE > 8支持documentFragment
                    fragment = document.createDocumentFragment();
                    while ((node = el.firstChild)) {
                        lastNode = fragment.appendChild(node);
                    }
                    range.insertNode(fragment);
                    if (lastNode) {
                        range = range.cloneRange();
                        range.setStartAfter(lastNode);
                        range.collapse(true);
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }
                }
            } else if (document.selection && document.selection.type != 'Control') {
                // IE < 9
                document.selection.createRange().pasteHTML(html);
            }
        },
        //弹出框确认按钮
        dialogSave(formRef) {
            // let content_html = document.querySelector("#AlarmSmsTemplate_add").innerHTML;
            this.$refs[formRef].validate(valid => {
                // 用户点击确定，验证是否输入模板名称
                if (valid) {
                    // 用户点击确定，再次验证是否输入模板内容
                    let content = document.querySelector('#AlarmSmsTemplate_add').innerText;
                    // 后台存储content的html代码，用于编辑回显处理
                    let content_html = document.querySelector('#AlarmSmsTemplate_add').innerHTML;
                    if (content === '') {
                        this.$alert('请输入短信模板内容', '系统提示', {
                            confirmButtonText: '确定'
                            // callback: action => {}
                        });
                    } else {
                        let validateForm = this.$refs[formRef];
                        if (content.length <= 100) {
                            // 验证通过，发起提交
                            this.$emit('dialogSave', validateForm, this.ruleForm, content, content_html);
                        } else {
                            this.$alert('请输入0-100以内个字数', '系统提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    // 验证不通过，数据截取操作
                                    let Scontent = content.substr(0, 100);
                                    let reg = /(\w*)<姓名>(.*)<人员类型>(.*)<报警类型>(.*)<区域名称>(.*)/g;
                                    let test = Scontent.replace(
                                        reg,
                                        '$1<span class="boxspan" style="display: inline-block; color:#158b91" contenteditable="false">&lt;姓名&gt;</span>$2<span class="boxspan" style="display: inline-block; color:#158b91" contenteditable="false">&lt;人员类型&gt;</span>$3<span class="boxspan" style="display: inline-block; color:#158b91" contenteditable="false">&lt;报警类型&gt;</span>$4<span class="boxspan" style="display: inline-block; color:#158b91" contenteditable="false">&lt;区域名称&gt;</span>'
                                    );
                                    this.msgStr = test;
                                    // 调用数据处理，进行示例: 数据同步
                                    this.$nextTick(() => {
                                        this.loginnowkeyup();
                                    });
                                }
                            });
                        }
                    }
                } else {
                    this.$message({message: '请输入短信模板名称!!',type: "error",showClose: true});
                    return false;
                }
            });
        },
        //弹出框取消按钮
              handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        }

    }
};
</script>
<style scoped lang="scss">
@import '~@/assets/css/cssConstant.scss';
/deep/.el-dialog{
    width: 870px;
}
#AlarmSmsTemplate {
    width: 830px;
    margin-top: 10px;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt {
    width: 100%;
    height: 140px;
    display: flex;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt .AlarmSmsTemplate_title {
    width: 90px;
    display: flex;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt .AlarmSmsTemplate_title div {
    margin-left: 4px;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_add {
    width: 430px;
    height: 100%;
    // border: 1px solid #158b91;
    // border: 1px solid $bd_input_skinThree_1;
    box-sizing: border-box;
    overflow-x: hidden;
    text-align: left;
    padding: 0 15px;
}
#AlarmSmsTemplate .leftbox_text {
    width: 430px;
    height: 75px;
    padding: 0 15px;
    margin-left: 90px;
    margin-top: 5px;
    box-sizing: border-box;
    overflow-x: hidden;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_add:focus {
    outline: none;
    border: 1px solid $bd_bright_skinThree_1;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt .AlarmSmsTemplate_add_blue:focus {
    outline: none;
    border: 1px solid $bd_bright_skinTwo_1!important;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_rightbox {
    width: 310px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-top: 10px;
    padding-left: 40px;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_rightbox .rightbox__btn {
    display: flex;
    flex-wrap: wrap;
    padding-top: 10px;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_rightbox .rightbox__btn .el-button {
    margin: 5px;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_add .boxspan {
    display: inline-block;
    color: #158b91;
    cursor: move;
}
#AlarmSmsTemplate .AlarmSmsTemplate_cnt #AlarmSmsTemplate_add .creatspan {
    display: inline-block;
    color: #158b91;
    cursor: move;
}
.zhfz_systemSetting .bd_input {
    border: 1px solid #158b91;
}
</style>